package springboot.controller;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springboot.bean.User;
import springboot.config.DelayRabbitMQConfig;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * 消息的发送方只需要指定  交换机,路由,消息本身
 */
@Slf4j
@RestController
@RequestMapping("/ttl")
public class RabbitMQController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping(value = "/sendMsg/{ttl}",method = RequestMethod.GET)
    public String sendMSG(@PathVariable String ttl) throws UnsupportedEncodingException {
        User user=new User();
        user.setId(1);
        user.setName("song");
        user.setAge(18);
        String jsonOutput=JSON.toJSONString(user);
        /*将消息发送给两个队列*/
        rabbitTemplate.convertAndSend("X","XA",jsonOutput);
        rabbitTemplate.convertAndSend("X","XB",jsonOutput);
        log.info("当前时间{},发送消息给QC队列,发送延时时长{}",new Date(),ttl);
        /*设置发送消息的存活时间 time to live(ttl)*/
        MessagePostProcessor messagePostProcessor= setProperties->{
            setProperties.getMessageProperties().setExpiration(ttl);
          return  setProperties;
        };
        rabbitTemplate.convertAndSend("X","XC",jsonOutput,messagePostProcessor);
        return "success";
    }
    @RequestMapping(value = "/sendDelayMessage/{message}/{delayTime}",method = RequestMethod.GET)
    public String sendDelayMessage(@PathVariable String message,@PathVariable Integer delayTime){
        /*设置发送消息的延时时间*/
        MessagePostProcessor messagePostProcessor=msgSet->{
            msgSet.getMessageProperties().setDelay(delayTime);
          return msgSet;
        };
        log.info("当前时间为{},发送的消息为{},延时的时间为{}ms",new Date(),message,delayTime);
        /*每个参数的意义可以直接进入形参看参数的意义*/
        rabbitTemplate.convertAndSend(DelayRabbitMQConfig.DELAY_EXCHANGE,DelayRabbitMQConfig.DELAY_ROUTING_KEY,message,messagePostProcessor);
        return "success";
    }
}
